<template>
  <div>
    <!--上方搜索框-->
    <el-form :inline="true" :model="keyword" ref="searchForm" class="demo-form-inline">
      <el-form-item>
        <el-button type="danger" size="small" @click="deleteBatch" icon="el-icon-delete">删除勾选</el-button>
        <el-button type="warning" size="small" @click="openAddDialog" icon="el-icon-plus">添加</el-button>
      </el-form-item>
      <el-form-item label="商品ID" prop="poNum">
        <el-input size="small" clearable v-model="keyword.poNum" placeholder="商品ID"></el-input>
      </el-form-item>
      <el-form-item label="商品名" prop="pname">
        <el-input size="small" clearable v-model="keyword.pname" placeholder="商品名"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="small" @click="search" icon="el-icon-search">查询</el-button>
        <el-button type="primary" plain size="small" @click="resetSearchForm('searchForm')" icon="el-icon-refresh">
          重置
        </el-button>
        <!-- <el-button type="primary" plain size="small" @click="downloadExcel" icon="el-icon-download">导出</el-button> -->
      </el-form-item>
    </el-form>

    <!-- 表格 -->
    <el-table v-loading="loading" :data="measureList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="采购单编号" align="center" prop="poNum" />
      <el-table-column label="供应商公司" align="center" prop="supplierCompany" />
      <el-table-column label="供应商姓名" align="center" prop="sname" />
      <el-table-column label="订单完成状态" align="center" prop="finishFlag">
        <template slot-scope="scope">
          <el-tag :type="scope.row.enableFlag == 'Y' ? '' : 'danger'">
            <span>{{ scope.row.enableFlag == 'Y' ? '是' : '否' }}</span>
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="产品ID" align="center" prop="pid" />
      <el-table-column label="产品名称" align="center" prop="pname" />
      <el-table-column label="产品单价" align="center" prop="price" />
      <el-table-column label="采购数量" align="center" prop="num" />
      <el-table-column label="单位" align="center" prop="unit" />
      <el-table-column label="总价" align="center" prop="money" />
      <el-table-column label="创建时间" align="center" prop="createTime" />

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <!-- <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['md:measure:edit']">修改</el-button> -->
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['md:measure:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
      :page-sizes="[5, 10, 15]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total">
    </el-pagination>


    <!-- 添加对话框 -->
    <el-dialog :title="title" :visible.sync="dialogFormVisible" width="40%">
      <el-form :model="POList" ref="poFormRef">

        <el-form-item label="订单号" prop="poNum">
          <el-input v-model="POList.poNum" autocomplete="off" style="width:300px"></el-input>
        </el-form-item>

        <el-form-item label="供应商公司" prop="sid">
          <el-select v-model="POList.sid" placeholder="请选择">
            <el-option v-for="item in supplierOptions" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
          <!-- <el-input v-model="salesorderlist.cName" autocomplete="off" style="width:300px" ></el-input> -->
        </el-form-item>

        <el-form-item label="完成状态" prop="finishFlag">
          <el-select v-model="POList.finishFlag" placeholder="请选择" disabled>
            <el-option
              v-for="item in finishFlagOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="产品编码" prop="pNum">
          <el-input v-model="POList.pcode" autocomplete="off" style="width:300px" disabled></el-input>
        </el-form-item>
        <el-form-item label="产品名称" prop="pid">
          <el-select v-model="POList.pid" placeholder="请选择" @change="handleProductChange">
            <el-option v-for="item in productOptions" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
          <!-- <el-input v-model="salesorderlist.pname" autocomplete="off" style="width:300px" ></el-input> -->
        </el-form-item>
        <el-form-item label="产品单价" prop="price">
          <el-input v-model="POList.price" autocomplete="off" style="width:300px"></el-input>
        </el-form-item>
        <el-form-item label="采购数量" prop="num">
          <el-input v-model="POList.num" autocomplete="off" style="width:300px"></el-input>
        </el-form-item>
        <el-form-item label="单位" prop="unit">
          <el-input v-model="POList.unit" autocomplete="off" style="width:300px"></el-input>
        </el-form-item>
        <el-form-item label="总价" prop="money ">
          <el-input v-model="POList.money" @focus="calculateMoney" autocomplete="off" style="width:300px" readonly>
          </el-input>
        </el-form-item>
        <!-- 创建时间 -->
        <el-form-item label="创建时间" prop="createTime">
          <el-date-picker v-model="POList.createTime" type="date" placeholder="选择日期时间" value-format="yyyy-MM-dd"
            style="width: 300px">
          </el-date-picker>
        </el-form-item>

      </el-form>


      <div>
        <el-button type="primary" @click="addPOList">提交</el-button>
        <el-button @click="dialogFormVisible = false">取 消</el-button>
      </div>
    </el-dialog>


  </div>
</template>

<script>


import { getAll, deleteById, deleteByIds, addPOList, getSupplierList, getProductList } from '@/api/PO';

export default {
  data() {
    return {
      supplierOptions: [],
      productOptions: [],
      dialogExcelVisible: false,
      pageNum: 1,
      pageSize: 10,
      total: 0,
      loading: false,
      currentPage: 1,
      keyword: {
        poNum: '',
        pname: ''
      },
      selectionRowArr: [],
      ids: [],
      dialogFormVisible: false,
      title: '添加单位',


      POList: {
        poNum: '',
        sid: '', // 替换 sId 为 sid
        sname: '',
        finishFlag: '0',
        pid: '', // 替换 pId 为 pid
        pcode: '',
        num: '',
        price: '',
        unit: '',
        money: '',
        remark: ''
      },


      finishFlagOptions: [
        {
          label: '未完成',
          value: '0'
        }, {
          label: '已完成',
          value: '1'
        }
      ]
    }


  },
  methods: {
    // 表单验证并提交
    addPOList() {
      this.$refs.poFormRef.validate(valid => {
        if (valid) {
          console.log("line 252 ", this.POList)
          addPOList(this.POList).then(res => {
            if (res.code == 200) {
              this.$message.success('添加成功')
              this.resetForm();
              this.dialogFormVisible = false
              this.getPOList()

            } else {
              this.$message.error('添加失败')
              this.resetForm();
            }
          })
        } else {
          console.log('验证失败');
          return false;
        }
      });
    },
    
    // 修复 handleProductChange 方法
    handleProductChange(productId) {
      const selectedProduct = this.productOptions.find(item => item.value === productId);
      if (selectedProduct) {
        this.POList.pcode = selectedProduct.pcode;
        this.POList.unit = selectedProduct.unit;
        this.POList.price = selectedProduct.price;
      }
    },
    // 获取列表    
    getPOList() {
      this.loading = true
      getAll({
        pname: this.keyword.pname,
        poNum: this.keyword.poNum,
        pageNum: this.pageNum,
        pageSize: this.pageSize
      }).then(response => {
        console.log("hou duan fan hui biao ge:", response.data.list)
        this.measureList = response.data.list
        this.total = response.data.total
        this.currentPage = response.data.currentPage
        this.loading = false
      })
    },

    handleSizeChange(val) {
      this.pageSize = val
      this.getPOList()
    },
    handleCurrentChange(val) {
      this.pageNum = val
      this.getPOList()
    },

    //获取选中checkbox的框的id
    handleSelectionChange(selectionRowArr) {
      this.ids = [];
      for (let i = 0; i < selectionRowArr.length; i++) {
        this.ids.push(selectionRowArr[i].id)
      }
    },


    //查詢
    search() {
      this.pageNum = 1
      this.getPOList()
    },
    // 重置表单
    resetSearchForm(formName) {
      this.$refs[formName].resetFields();//校验
      this.getPOList()
    },


    //删除
    handleDelete(row) {
      console.log("line215", row)
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteById({ id: row.id }).then(res => {
          console.log("md line 181:", res)
          if (res.code == 200) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.getPOList();
          } else {
            this.$message({
              type: 'error',
              message: '删除失败!'
            });
          }
        })
      })
    },


    // 批量删除
    deleteBatch() {
      console.log("md line 167:", this.ids)
      this.$confirm('此操作将永久删除' + this.ids.length + '条数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        //delBatch  刚才api/unit.js中一个axios方法
        deleteByIds(this.ids).then(response => {
          console.log("md line 151:", response)
          if (response.code == 200) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
          }
          this.getPOList()
        })
      })
    },




    poList() {
      this.$refs.poFormRef.validate(valid => {
        if (valid) {
          // 提交表单逻辑
          console.log('提交采购单：', this.poForm);
          this.$message.success('提交成功！');
          this.dialogFormVisible = false;
          // 调用API保存数据
          // savePO(this.poForm).then(...)
        } else {
          console.log('表单校验失败');
          return false;
        }
      });
    },

    openAddDialog() {
      this.title = '添加'
      this.dialogFormVisible = true
      this.generatePONumber()
      console.log("md line311:", this.POList)
      this.getSupplierData()
      this.getProductData()
      this.salesorderlist.finishFlag = '0'
    },

    // 生成订单号
    generatePONumber() {
      const prefix = 'PO';
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份从0开始
      const day = String(now.getDate()).padStart(2, '0');
      const hours = String(now.getHours()).padStart(2, '0');
      const minutes = String(now.getMinutes()).padStart(2, '0');
      const seconds = String(now.getSeconds()).padStart(2, '0');
      console.log(`${prefix}${year}${month}${day}${hours}${minutes}${seconds}`)
      var myPONum = `${prefix}${year}${month}${day}${hours}${minutes}${seconds}`
      this.POList.poNum = myPONum
    },


    //计算总价
    calculateMoney() {
      const price = parseFloat(this.POList.price) || 0;
      const pnum = parseInt(this.POList.num) || 0;
      this.POList.money  = (price * pnum).toFixed(2);
    },

    // 重置表单方法
    resetForm() {
      this.POList = {
        poNum: '',
        supplierCompany: '',
        sname: '',
        finishFlag: '0',
        pid: '',
        pname: '',
        num: '',
        price: '',
        unit: '',
        money: '',
        remark: ''
      };
    },

    // 获取供应商数据
    getSupplierData() {
      getSupplierList().then(response => {
        this.supplierOptions = response.data.map(item => ({
          value: item.id,
          label: item.company
        }))
      })
    },

    //获取商品数据
    getProductData() {
      getProductList().then(response => {
        console.log("index line366", response)
        this.productOptions = response.data.map(item => ({
          value: item.id,
          label: item.name,
          pcode: item.pcode,
          unit: item.unit,
          price: item.price
        }))
        console.log("index line369", this.productOptions)
      })
    }
  },


  created() {
    this.getPOList()
  },
  computed: {
    money: function () {
      return this.POList.price * this.POList.num;
    }
  },


  //添加
   addPOList() {
      console.log("line 252 ", this.POList)
      addPOList(this.POList).then(res => {
        if (res.code == 200) {
          this.$message.success('添加成功')
          this.resetForm();
          this.dialogFormVisible = false
          this.getPOList()

        } else {
          this.$message.error('添加失败')
          this.resetForm();
        }
      })
    },

    /* downloadExcel() {
         this.$confirm('确定要导出数据吗?', '信息', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
  
          // 方案1: 原生js方式发起导出excel请求,后端设置响应格式
          window.location.href = "http://localhost:8888/po/downloadexcel"
          // 方案1的话后端需要设置响应格式和内容
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消导出数据！'
          })
        })
      } */
}
</script>

<style lang="scss" scoped></style>